<!--
 * @Author: xjt
 * @Date: 2020-12-09 11:28:58
 * @LastEditTime: 2021-04-27 14:37:18
 * @Description: 决算弹窗组件，支持新增、编辑、查看
-->
<template>
  <div class="addDialog" :class="{previewPage: isReadonly}">
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="1200px"
      @close="handleClosed"
      class="basic-form"
    >
      <div class="dialogWrap">
        <el-form ref="dialogForm" :rules="rules" :model="formData" class="form-wrap">
          <h4 class="dialogItemTitle full">合同信息</h4>
          <div class="listFormItem">
            <el-button class="add" size="mini" type="primary" @click="$refs.chooseDialog.show()" v-if="!isReadonly">选择合同</el-button>
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-halfCharCode v-model="formData.contractNo" maxlength="20" readonly placeholder="请选择合同编号" />
            </el-form-item>
          </div>
          <el-form-item label="合同乙方" prop="unitName">
            <el-input v-halfCharCode v-model="formData.unitName" maxlength="20" readonly placeholder="请输入合同乙方" />
          </el-form-item>
          <el-form-item label="合同签订日期" prop="signingDate">
            <el-date-picker v-model="formData.signingDate" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择签订日期" disabled />
          </el-form-item>
          <div class="listFormItem">
            <el-form-item label="物业名称" prop="propertyName">
              <el-input v-halfCharCode v-model="formData.propertyName" maxlength="99" readonly placeholder="请输入物业名称" />
            </el-form-item>
          </div>
          <el-form-item class="full" label="物业地址" prop="propertyAddress">
            <el-input v-halfCharCode v-model="formData.propertyAddress" maxlength="99" readonly placeholder="请输入物业地址" />
          </el-form-item>
          <h4 class="dialogItemTitle full">结算情况</h4>
          <el-form-item label="结算日期" prop="settlementDate">
            <el-date-picker v-model="formData.settlementDate" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择结算日期" :disabled="isReadonly" />
          </el-form-item>
          <el-form-item label="结算单位" prop="settlementUnit">
            <el-input v-halfCharCode v-model="formData.settlementUnit" maxlength="20" placeholder="请输入结算单位" :readonly="isReadonly" />
          </el-form-item>
          <el-form-item label="送审金额(元)" prop="settlementReviewAmount">
            <el-input
              v-model="formData.settlementReviewAmount"
              maxlength="15"
              v-only-number="{min:0, precision:2}"
              placeholder="请输入送审金额"
              :readonly="isReadonly"
              v-if="!isReadonly"
            />
            <el-input :value="formData.settlementReviewAmount | thousandMoney" v-else />
          </el-form-item>
          <el-form-item label="核减金额(元)" prop="settlementSubtractAmount">
            <el-input
              v-model="formData.settlementSubtractAmount"
              maxlength="15"
              v-only-number="{min:0, precision:2}"
              placeholder="请输入核减金额"
              v-if="!isReadonly"
            />
            <el-input :value="formData.settlementSubtractAmount | thousandMoney" v-else />
          </el-form-item>
          <el-form-item label="审定金额(元)" prop="settlementAuthorizedAmount">
            <el-input
              v-model="formData.settlementAuthorizedAmount"
              maxlength="15"
              v-only-number="{min:0, precision:2}"
              placeholder="请输入审定金额"
              v-if="!isReadonly"
            />
            <el-input :value="formData.settlementAuthorizedAmount | thousandMoney" v-else />
          </el-form-item>
          <el-form-item label="核减率" prop="settlementSubtractRate">
            <el-input
              v-halfCharCode
              disabled
              v-model="formData.settlementSubtractRate"
              maxlength="15"
              oninput="value = value.replace(/[^0-9.%]/g,'')"
              placeholder="请输入核减率"
              :readonly="isReadonly"
            />
          </el-form-item>
          <el-form-item label="审核公司" prop="settlementAuditCompany">
            <el-input v-halfCharCode v-model="formData.settlementAuditCompany" maxlength="15" placeholder="请输入审核公司" :readonly="isReadonly" />
          </el-form-item>
          <h4 class="dialogItemTitle full">决算情况</h4>
          <el-form-item label="决算日期" prop="finalDate">
            <el-date-picker v-model="formData.finalDate" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择决算日期" :disabled="isReadonly" />
          </el-form-item>
          <el-form-item label="决算单位" prop="finalUnit">
            <el-input v-halfCharCode v-model="formData.finalUnit" maxlength="20" placeholder="请输入决算单位" :readonly="isReadonly" />
          </el-form-item>
          <el-form-item label="送审金额(元)" prop="finalReviewAmount">
            <el-input
              v-model="formData.finalReviewAmount"
              maxlength="15"
              v-only-number="{min:0, precision:2}"
              placeholder="请输入送审金额"
              v-if="!isReadonly"
            />
            <el-input :value="formData.finalReviewAmount | thousandMoney" v-else />
          </el-form-item>
          <el-form-item label="核减金额(元)" prop="finalSubtractAmount">
            <el-input
              v-model="formData.finalSubtractAmount"
              maxlength="15"
              v-only-number="{min:0, precision:2}"
              placeholder="请输入核减金额"
              v-if="!isReadonly"
            />
            <el-input :value="formData.finalSubtractAmount | thousandMoney" v-else />
          </el-form-item>
          <el-form-item label="审定金额(元)" prop="finalAuthorizedAmount">
            <el-input
              v-model="formData.finalAuthorizedAmount"
              maxlength="15"
              v-only-number="{min:0, precision:2}"
              placeholder="请输入审定金额"
              v-if="!isReadonly"
            />
            <el-input :value="formData.finalAuthorizedAmount | thousandMoney" v-else />
          </el-form-item>
          <el-form-item label="核减率" prop="finalSubtractRate">
            <el-input
              v-halfCharCode
              disabled
              v-model="formData.finalSubtractRate"
              maxlength="15"
              oninput="value = value.replace(/[^0-9.%]/g,'')"
              placeholder="请输入核减率"
              :readonly="isReadonly"
            />
          </el-form-item>
          <el-form-item label="审核公司" prop="finalAuditCompany">
            <el-input v-halfCharCode v-model="formData.finalAuditCompany" maxlength="15" placeholder="请输入审核公司" :readonly="isReadonly" />
          </el-form-item>
          <!-- 附件 -->
          <div class="full" v-if="dialogVisible">
            <div v-if="oldFiles.length || type !== 'preview'">
              <h4 class="dialogItemTitle">上传附件</h4>
            </div>
            <v-upload
              ref="upload"
              :busId="formData.paymentSettlementId"
              modelType="paymentAccount"
              @onSuccess="onSuccess"
              @loadCompleted="handleLoadCompleted"
              v-model="uploadFileList"
              :isView="['preview'].includes(type)"
              :canDelete="['add','edit'].includes(type)"
            />
          </div>
        </el-form>
        <!-- 选择弹窗 -->
        <choose-dialog ref="chooseDialog" v-bind="chooseDialogAttrs" @chooseData="handleChoose" />
      </div>
      <div slot="footer">
        <el-button @click="$bus.$emit('operationLog',formData.paymentContractId)" v-if="type==='preview'">操作日志</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editContract, checkAccountContractNo, editAccount, getAccountById } from "@/views/wy-operate/api/payment";
export default {
  name: "accountDialog",
  inject: ['initList'],
  data () {
    return {
      //弹窗类型，默认新增
      type: "add",
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        // 	决算-审定金额
        finalAuthorizedAmount: '',
        // 	决算日期
        finalDate: "",
        // 决算-送审金额
        finalReviewAmount: '',
        // 决算-核减金额
        finalSubtractAmount: 0,
        // 决算单位
        finalUnit: "",
        // 决算-核减率
        finalSubtractRate: "",
        // 决算-审核公司
        finalAuditCompany: "",
        // 付款合同主键
        paymentContractId: "",
        // 主键
        paymentSettlementId: "",
        //	结算-审定金额
        settlementAuthorizedAmount: '',
        // 结算日期
        settlementDate: "",
        // 结算-送审金额
        settlementReviewAmount: '',
        // 结算-核减金额
        settlementSubtractAmount: 0,
        // 结算单位
        settlementUnit: "",
        // 结算-核减率
        settlementSubtractRate: "",
        // 结算-审核公司
        settlementAuditCompany: "",
        // 合同编号
        contractNo: '',
        // 合同乙方
        unitName: '',
        // 物业名称
        propertyName: '',
        // 物业地址
        propertyAddress: ''
      },
      // 上传文件列表
      uploadFileList: [],
      // 已上传的文件
      oldFiles: [],
      // 校验
      rules: {
        contractNo: [
          { required: true, message: "合同编号不能为空", trigger: "blur" },
          { validator: this.handleContractNoRepeat, trigger: 'blur' },
        ],
        unitName: [{ required: true, message: "合同乙方不能为空", trigger: "blur" }],
        signingDate: [{ required: true, message: "签订日期不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        propertyAddress: [{ required: true, message: "物业地址不能为空", trigger: "blur" }],
        // 结算
        settlementDate: [{ required: true, message: "结算日期不能为空", trigger: "blur" }],
        settlementUnit: [{ required: true, message: "结算单位不能为空", trigger: "blur" }],
        settlementReviewAmount: [{ required: true, message: "送审金额不能为空", trigger: "blur" }],
        //settlementSubtractAmount: [{ validator: this.settlementSubtractAmountValidator, trigger: 'blur' }],
        settlementAuthorizedAmount: [
          { required: true, message: "审定金额不能为空", trigger: "blur" },
          { validator: this.settlementSubtractAmountValidator, trigger: 'blur' }
        ],
        // 决算
        finalDate: [{ required: true, message: "结算日期不能为空", trigger: "blur" }],
        finalUnit: [{ required: true, message: "结算单位不能为空", trigger: "blur" }],
        finalReviewAmount: [{ required: true, message: "送审金额不能为空", trigger: "blur" }],
        //finalSubtractAmount: [{ validator: this.settlementSubtractAmountValidator, trigger: 'blur' }],
        finalAuthorizedAmount: [
          { required: true, message: "审定金额不能为空", trigger: "blur" },
          { validator: this.handleSubtractAmount, trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增"
      }[this.type];
    },
    // 判断是否只读
    isReadonly () {
      return ["preview"].includes(this.type);
    },
    // 合同类型
    contractTypes () {
      return this.getDict('payment-contract-type')
    },
    // 选择弹窗属性数据
    chooseDialogAttrs () {
      const contractTypeFormatter = (row, column, cellValue) => {
        if (this.contractTypes.length === 0) return '';
        let type = this.contractTypes.find(item => item.value == cellValue)
        return type ? type.label : '';
      }
      return {
        title: '选择合同',
        placeholder: '请输入单位名称',
        url: '/api/payment/contract/settlement/registration/contractList',
        primaryKey: 'paymentContractId',
        width: "1200px",
        showData: [
          { prop: 'contractNo', label: '合同编号', width: '200', align: 'center' },
          { prop: 'contractType', label: '合同类型', width: '200', align: 'center', formatter: contractTypeFormatter },
          { prop: 'propertyName', label: '物业名称', width: '140', align: 'center' },
          { prop: 'unitName', label: '乙方单位名称', width: '200', align: 'center' },
        ],
        returnData: ['contractNo', 'contractType', 'paymentContractId', 'paymentContractUnitId', 'propertyAddress', 'propertyName', 'roomId', 'unitName', 'signingDate'],
      }
    }
  },
  watch: {
    'formData.settlementSubtractAmount': function () {
      this.formData.settlementSubtractRate = (Number(this.formData.settlementSubtractAmount) / Number(this.formData.settlementReviewAmount) * 100).toFixed(2) + '%'
    },
    'formData.settlementReviewAmount': function () {
      this.formData.settlementSubtractRate = (Number(this.formData.settlementSubtractAmount) / Number(this.formData.settlementReviewAmount) * 100).toFixed(2) + '%'
    },
    'formData.finalSubtractAmount': function () {
      this.formData.finalSubtractRate = (Number(this.formData.finalSubtractAmount) / Number(this.formData.finalReviewAmount) * 100).toFixed(2) + '%'
    },
    'formData.finalReviewAmount': function () {
      this.formData.finalSubtractRate = (Number(this.formData.finalSubtractAmount) / Number(this.formData.finalReviewAmount) * 100).toFixed(2) + '%'
    }
  },
  methods: {
    //开启弹窗
    show ({ type, data = {} }) {
      if (['preview', 'edit'].includes(type)) {
        getAccountById(data.paymentSettlementId).then(res => {
          this.formData = { ...this.formData, ...res.data.data };
          this.$nextTick(() => {
            this.$refs.upload.getFiles()
          })
        })
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    save () {
      if (['edit', 'add'].includes(this.type)) {
        this.$refs.dialogForm.validate(validate => {
          validate && this.$refs.upload.submit();
        })
      }
    },
    // 上传成功
    async onSuccess (response, file, fileList) {
      let params = this.type == 'add' ? { ...this.formData, paymentSettlementId: response.data } : JSON.parse(JSON.stringify(this.formData))
      params.settlementSubtractAmount = params.settlementSubtractAmount || 0
      params.finalSubtractAmount = params.finalSubtractAmount || 0
      const res = await editAccount(params, this.type)
      if (res.data.code == 0) {
        this.$message.success(`${this.dialogTitle}成功!`);
        this.initList({ keyword: '', current: 1 })
        this.dialogVisible = false;
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 弹窗关闭还原
    handleClosed () {
      this.uploadFileList = []
      this.formData = {
        finalAuthorizedAmount: '',
        finalDate: "",
        finalReviewAmount: '',
        finalSubtractAmount: 0,
        finalUnit: "",
        finalSubtractRate: "",
        finalAuditCompany: "",
        paymentContractId: "",
        paymentSettlementId: "",
        settlementAuthorizedAmount: '',
        settlementDate: "",
        settlementReviewAmount: '',
        settlementSubtractAmount: 0,
        settlementUnit: "",
        settlementSubtractRate: "",
        settlementAuditCompany: "",
        contractNo: '',
        unitName: '',
        propertyName: '',
        propertyAddress: ''
      }
      this.$refs.dialogForm.resetFields();
    },
    // 监听上传组件上传完成
    handleLoadCompleted (data) {
      this.oldFiles = data
    },
    // 监听弹窗选中
    handleChoose (data) {
      this.formData = { ...this.formData, ...data }
    },
    // 校验合同编号是否重复
    handleContractNoRepeat (rule, value, callback) {
      let params = { paymentContractId: this.formData.paymentContractId }
      if (this.type === 'edit') {
        params.paymentSettlementId = this.formData.paymentSettlementId
      }
      checkAccountContractNo(params, this.type).then(res => {
        if (res.data.code == 0 && res.data.data) {
          return callback()
        }
        return callback(new Error('该合同已决算,请选择其他合同'))
      })
    },
    // 送审金额改变监听【需求待确认中】
    handleReviewAmountChange (val, type) {
      // 结算情况
      if (type === 'selttlement') {

      }
      // 决算情况
      if (type === 'account') {

      }
    },
    // 决算审定金额校验
    handleSubtractAmount (rule, value, callback) {
      if (value != Number(this.formData.finalReviewAmount) - Number(this.formData.finalSubtractAmount)) {
        callback(new Error('审定金额必须等于送审金额减去核减金额'))
      }
      callback()
    },
    // 结算-核减金额校验
    settlementSubtractAmountValidator (rule, value, callback) {
      if (value != Number(this.formData.settlementReviewAmount) - Number(this.formData.settlementSubtractAmount)) {
        callback(new Error('审定金额必须等于送审金额减去核减金额'))
      }
      callback()
    },
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-dialog__body {
    padding: 16px 32px;
  }
}
</style>
